<template>
  <div class="app-container">
    <div class="flex-between">
      <div class="flex-between">
        <el-button
          type="primary"
          @click="handleInMedicine"
        >药品入库</el-button>
        <el-button
          type="danger"
          @click="handleOutMedicine"
        >药品出库</el-button>
      </div>
      <el-input
        v-model="search"
        class="search-main"
        placeholder="请输入药品名字查询"
        prefix-icon="el-icon-search"
        @keyup.enter.native="HandleSearch"
      />
    </div>
    <el-table
      ref="medicineList"
      :data="medicineList"
      style="width: 100%;margin-top:30px;"
    >
      <el-table-column
        align="center"
        label="药品名称"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="药品编号"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="药品库存"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row.number }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="厂家"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row.factory }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="售价"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row.sellingPrice }}
        </template>
      </el-table-column>
      <el-table-column
        align="header-center"
        label="最后一次录入时间"
      >
        <template slot-scope="scope">
          {{ scope.row.updateTime }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope)"
          >修改</el-button>
          <template v-if="scope.row.disable === 1">
            <el-button
              type="success"
              size="small"
              @click="handleDelete2(scope)"
            >解禁</el-button>
          </template>
          <template v-if="scope.row.disable === 0">
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope)"
            >禁用</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      :current-page="pageNum"
      :page-size="pageSize"
      layout="total,sizes,  prev, pager, next, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      :visible.sync="dialogRuku"
      :title="'入库操作'"
    >
      <el-tabs
        v-model="activeName"
        @tab-click="handleClickRuku"
      >
        <el-tab-pane
          label="入库原有药品"
          name="first"
        >
          <el-form
            :model="medicine"
            label-width="80px"
            label-position="left"
          >
            <el-form-item
              label="名称"
              required
            >
              <el-input
                v-model="medicine.shortName"
                class="medicine-input"
                placeholder="请选择药品"
                suffix-icon="el-icon-bank-card"
                @click.native="dialogMedicine=true"
              />
            </el-form-item>
            <el-form-item
              label="名称"
              required
            >
              <el-input
                v-model="medicine.name"
                placeholder="请输入药品详细名称"
                :disabled="true"
              />
            </el-form-item>
            <el-form-item label="编号">
              <el-input
                v-model="medicine.code"
                placeholder="请输入药品编号"
                :disabled="true"
              />
            </el-form-item>
            <el-form-item
              label="数量"
              required
            >
              <el-input
                v-model="medicine.number"
                placeholder="请输入进货数量"
                type="number"
                required
              />
            </el-form-item>
            <el-form-item label="厂家">
              <el-input
                v-model="medicine.factory"
                placeholder="请输入厂家名称"
                :disabled="true"
              />
            </el-form-item>
            <el-form-item label="售价">
              <el-input
                v-model="medicine.sellingPrice"
                placeholder="请输入药品售价"
                :disabled="true"
                required
              />
            </el-form-item>
            <el-form-item
              label="进价"
              required
            >
              <el-input
                v-model="medicine.purchasePrice"
                placeholder="请输入药品进价"
              />
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="medicine.remark"
                placeholder="请输入备注"
              />
            </el-form-item>
            <div style="text-align:right;">
              <el-button
                type="danger"
                @click="dialogRuku=false"
              >取消</el-button>
              <el-button
                type="primary"
                @click="confirmMedicine"
              >确定</el-button>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane
          label="入库新药品"
          name="second"
        >
          <el-form
            ref="rukuNewForm"
            :model="medicine"
            label-width="80px"
            label-position="left"
            :rules="rukuRules"
          >
            <el-form-item
              label="名称"
              prop="name"
              required
            >
              <el-input
                v-model="medicine.name"
                placeholder="请输入药品名称"
              />
            </el-form-item>
            <el-form-item label="编号">
              <el-input
                v-model="medicine.code"
                placeholder="请输入药品编号"
              />
            </el-form-item>
            <el-form-item
              label="数量"
              prop="number"
              required
            >
              <el-input
                v-model="medicine.number"
                placeholder="请输入进货数量"
              />
            </el-form-item>
            <el-form-item label="厂家">
              <el-input
                v-model="medicine.factory"
                placeholder="请输入厂家名称"
              />
            </el-form-item>
            <div
              v-for="(item,i) in jiageArr"
              :key="i"
            >
              <el-form-item
                :label="(i+1)+'级会员售价'"
                prop="sellingPrice"
                label-width="100px"
              >
                <el-col :span="8">
                  <el-input
                    v-model="item.value"
                    placeholder="请输入药品售价"
                    required
                    width="80%"
                    @change="handlerChangeShou"
                  />
                </el-col>
                <el-button
                  :icon="i==0?'el-icon-plus':'el-icon-minus'"
                  @click="handleH(i)"
                />
              </el-form-item>
            </div>
            <el-form-item
              label="进价"
              prop="purchasePrice"
            >
              <el-input
                v-model="medicine.purchasePrice"
                type="number"
                placeholder="请输入药品进价"
                required
                @change="handlerChangeJin"
              />
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="medicine.remark"
                placeholder="请输入备注"
              />
            </el-form-item>
            <div style="text-align:right;">
              <el-button
                type="danger"
                @click="dialogRuku=false"
              >取消</el-button>
              <el-button
                type="primary"
                @click="confirmMedicine"
              >确定</el-button>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>

    </el-dialog>
    <el-dialog
      :visible.sync="dialogChuku"
      :title="'出库操作'"
    >
      <el-form
        :model="medicine"
        label-width="80px"
        label-position="left"
      >
        <dnd-list
          :list1="list1"
          :prescription-id="prescriptionNewId"
          list1-title="出库的药品"
          list2-title="所有药品"
          @selectList2="selectList2"
        />
        <el-form-item label="备注">
          <el-input
            v-model="medicine.remark"
            placeholder="请输入备注"
          />
        </el-form-item>
        <div style="text-align:right;">
          <el-button
            type="danger"
            @click="dialogChuku=false"
          >取消</el-button>
          <el-button
            type="primary"
            @click="confirmMedicineChuku"
          >确定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      class="select-medicine-dialog"
      :visible.sync="dialogMedicine"
      :title="'选择药品'"
      width="80%"
      append-to-body
    >
      <mediceSelect
        @cancel="medicineCancel"
        @confirm="selectMedicine"
      />
    </el-dialog>
    <el-dialog
      class="select-medicine-dialog"
      :visible.sync="dialogPrescription"
      :title="'选择药方'"
      width="80%"
      append-to-body
    >
      <prescriptionSelect
        :payment="'0'"
        :type="'1'"
        @cancel="prescriptionCancel"
        @confirm="selectPrescription"
      />
    </el-dialog>
    <el-dialog
      :visible.sync="dialogBianji"
      :title="'编辑操作'"
    >
      <el-tabs
        v-model="activeName"
        @tab-click="handleClickRuku"
      >
        <el-form
          :model="medicine"
          label-width="80px"
          label-position="left"
        >
          <el-form-item
            label="名称"
            required
          >
            <el-input
              v-model="medicine.name"
              placeholder="请输入药品名称"
            />
          </el-form-item>
          <el-form-item label="编号">
            <el-input
              v-model="medicine.code"
              placeholder="请输入药品编号"
            />
          </el-form-item>
          <el-form-item
            label="库存"
            required
          >
            <el-input
              v-model="medicine.number"
              placeholder="库存"
              required
              :disabled="true"
            />
          </el-form-item>
          <el-form-item label="厂家">
            <el-input
              v-model="medicine.factory"
              placeholder="请输入厂家名称"
            />
          </el-form-item>
          <el-form-item label="售价">
            <el-input
              v-model="medicine.sellingPrice"
              placeholder="请输入药品售价"
              required
            />
          </el-form-item>
          <el-form-item
            label="进价"
            required
          >
            <el-input
              v-model="medicine.purchasePrice"
              placeholder="请输入药品进价"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="medicine.remark"
              placeholder="请输入备注"
            />
          </el-form-item>
          <div style="text-align:right;">
            <el-button
              type="danger"
              @click="dialogBianji=false"
            >取消</el-button>
            <el-button
              type="primary"
              @click="confirmEditorMedicine"
            >确定</el-button>
          </div>
        </el-form>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import search from '@/components/search'
import mediceSelect from '@/components/medicine'
import prescriptionSelect from '@/components/prescription'
import { deepClone } from '@/utils'
import { updateRole } from '@/api/role'
import { addMedicine, getMedicines, medicineCheckInOut, updateMedicine } from '@/api/medicine'
import { addPayment } from '@/api/pay'
import { addPrescription } from '@/api/prescription'
import DndList from '@/components/DndList'
import { timestampToTime } from '@/utils/time'

const defaultMedicine = {
  key: '',
  name: '',
  code: '',
  number: '',
  factory_id: '',
  selling_price: '',
  purchase_price: '',
  remake: ''
}
const defaultprescription = {
  adminInfoVO: {},
  userInfoVO: {}
}

export default {
  components: {
    search,
    mediceSelect,
    prescriptionSelect,
    DndList
  },
  data() {
    return {
      payMethodList: [
        { label: '现金', value: '1' },
        { label: '微信', value: '2' },
        { label: '支付宝', value: '3' },
        { label: '医保卡', value: '4' },
        { label: '其他', value: '5' }
      ],
      tabMapOptions: [
        { label: '当天', key: 'CN' },
        { label: '近一周', key: 'US' },
        { label: '近一月', key: 'JP' },
        { label: '所有', key: 'EU' }
      ],
      medicine: Object.assign({}, defaultMedicine),
      pay: {},
      routes: [],
      dialogMedicine: false,
      medicineList: [],
      dialogVisible: false,
      dialogRuku: false,
      dialogChuku: false,
      dialogType: 'new',
      dialogPrescription: false,
      dialogBianji: false,
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      list1: [],
      list2: [],
      tab: 'first',
      rukuRules: {
        name: [
          { required: true, message: '必填项必须填写', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '必填项必须填写', trigger: 'blur' }
        ],
        sellingPrice: [
          { required: true, message: '必填项必须填写', trigger: 'blur' }
        ],
        purchasePrice: [
          { required: true, message: '必填项必须填写', trigger: 'blur' }
        ]
      },
      chuku: false,
      search: '',
      activeName: 'first',
      pageNum: 1, // 默认每页显示1条数据
      pageSize: 10,
      loading: false,
      totalCount: 0,
      prescription: Object.assign({}, defaultprescription),
      prescriptionId: 0,
      prescriptionNewId: '0',
      prescriptionMedicineList: [],
      jiageArr: [{ key: 1, value: 0 }],
      payArr: [{ method: 1, payment: 0 }]
    }
  },
  async created() {
    // console.log(res)
    // Mock: get all routes and roles list from server
    // this.getRoutes()
    this.getMedicine({
      pageNum: this.pageNum,
      pageSize: this.pageSize
    })
    this.list2 = deepClone(this.medicineList)
  },
  methods: {
    async getMedicine(data) {
      const res = await getMedicines(data)
      this.medicineList = res.data.list
      for (const i in this.medicineList) {
        this.medicineList[i].key = i
        this.medicineList[i].updateTime = timestampToTime(this.medicineList[i].updateTime)
      }
      this.totalCount = res.data.total
    },
    handleAddMedicine() {
      this.medicine = Object.assign({}, this.medicine)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleInMedicine() {
      this.medicine = Object.assign({}, this.medicine)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogRuku = true
    },
    handleEdit(scope) { // 修改
      this.dialogType = 'edit'
      this.dialogBianji = true
      this.checkStrictly = true
      this.medicine = deepClone(scope.row)
      // this.$nextTick(() => {
      //   const routes = this.generateRoutes(this.role.routes)
      //   this.$refs.tree.setCheckedNodes(this.generateArr(routes))
      //   // set checked state of a node not affects its father and child nodes
      //   this.checkStrictly = false
      // })
    },
    async confirmEditorMedicine() { // 修改按钮
      // delete this.medicine.createTime
      // delete this.medicine.updateId
      delete this.medicine.updateTime
      const res = await updateMedicine(this.medicine)
      console.log(res)
      const medicineList = this.medicineList
      this.$notify({
        title: '修改成功',
        dangerouslyUseHTMLString: true,
        message: `
            <div>药品名称: ${this.medicine.name}</div>
          `,
        type: 'success'
      })
      for (let index = 0; index < medicineList.length; index++) {
        if (medicineList[index].key === this.medicine.key) {
          medicineList.splice(index, 1, Object.assign({}, this.medicine))
          break
        }
      }
      this.dialogBianji = false
    },
    handleDelete({ $index, row }) { // 删除操作
      this.$confirm('确定要禁用吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        console.log(row)
        row.disable = 1
        const data = {}
        data.id = row.id
        data.disable = 1
        await updateMedicine(data)
        this.medicineList[$index].disable = 1
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
        .catch(err => { console.error(err) })
    },
    handleDelete2({ $index, row }) { // 删除操作
      this.$confirm('确定要解除禁用吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        console.log(row)
        row.disable = 0
        const data = {}
        data.id = row.id
        data.disable = 0
        await updateMedicine(data)
        this.medicineList[$index].disable = 0
        this.$message({
          type: 'success',
          message: '解除成功!'
        })
      })
        .catch(err => { console.error(err) })
    },
    async confirmMedicine() { // 入库的确定按钮
      const _this = this
      if (this.tab === 'first') {
        this.ruku(this.medicine.id)
      } else {
        this.$refs.rukuNewForm.validate(async(valid) => {
          if (valid) {
            const { data } = await addMedicine(this.medicine)
            console.log(data)
            _this.ruku(data)
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    async ruku(medicineId) { // 入库
      const _this = this
      const dataRU = {
        adminId: _this.$store.state.user.adminId,
        mark: _this.medicine.remark,
        medicineId: medicineId,
        price: _this.medicine.purchasePrice,
        number: parseInt(this.medicine.number),
        type: 1
      }
      await medicineCheckInOut(dataRU)
      this.medicineList.unshift(this.medicine)
      const { name } = this.medicine
      this.dialogRuku = false
      this.$notify({
        title: '入库成功',
        dangerouslyUseHTMLString: true,
        message: `
            <div>药品名称: ${name}</div>
          `,
        type: 'success'
      })
    },
    async confirmMedicineChuku(type) { // 出库的确定按钮
      const data = {}
      data.paymentDetailVOList = []
      data.prescriptionId = this.prescriptionNewId
      // data.paymentDetailVOList.push({ method: this.pay.method, amount: this.pay.amount })
      data.paymentDetailVOList = this.payArr
      data.creator = this.$store.state.user.adminId
      data.registrationFee = this.registrationFee
      const res = await addPayment(data)
      this.$notify({
        title: '出库成功',
        dangerouslyUseHTMLString: true,
        message: `
          `,
        type: 'success'
      })
      this.dialogChuku = false
    },
    handleClickRuku(tab, event) { // 点击切换的时候
      this.tab = tab.name
      this.medicine = defaultMedicine
    },
    medicineCancel() { // 取消
      this.dialogMedicine = false
    },
    selectMedicine(data) { // 选择药品
      this.medicine = data
      this.dialogMedicine = false
    },
    prescriptionCancel() { // 取消药方的按钮
      this.dialogPrescription = false
    },
    handleSizeChange(page) { // 药品分页
      this.pageSize = page
      this.getMedicine({
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    },
    handleCurrentChange(page) { // 药品分页
      this.pageNum = page
      this.getMedicine({
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    },
    async selectPrescription(data) { // 选择药方以后
      this.prescription = data
      console.log(data)
      this.prescriptionMedicineList = data.prescriptionMedicineDTOList
      for (const i in this.prescriptionMedicineList) {
        this.prescriptionMedicineList[i].allPrice = Number(this.prescriptionMedicineList[i].sellingPrice) * Number(this.prescriptionMedicineList[i].number)
      }
      this.dialogPrescription = false
    },
    handlerChangeShou(val) {
      this.medicine.sellingPrice = Number(val).toFixed(2)
    },
    handlerChangeJin(val) {
      this.medicine.purchasePrice = Number(val).toFixed(2)
    },
    selectList2(data) {
      this.list2 = data
    },
    async HandleSearch() {
      this.getMedicine({
        name: this.search,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    },
    handleH(i) {
      console.log(i)
      if (i === 0 && this.jiageArr.length < 5) {
        this.jiageArr.push({ key: i, value: 0 })
      } else {
        this.jiageArr.splice(i, 1)
      }
    },
    handleP(i) {
      console.log(i)
      if (i === 0 && this.payArr.length < 5) {
        this.payArr.push({ method: 1, payment: 0 })
      } else {
        this.payArr.splice(i, 1)
      }
    },
    async  handleOutMedicine() {
      this.dialogChuku = true
      this.medicine = defaultMedicine
      var form = {}
      form.type = 2
      form.adminName = this.$store.state.user.adminId
      const { data } = await addPrescription(form)
      console.log(data)
      this.prescriptionNewId = data.toString()
    }
  }
}
</script>

<style lang="scss">
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}

.medicine-input .el-input__inner {
  cursor: pointer;
}
.select-medicine-dialog {
  // width: 100%;
  height: 90vh;
  overflow: auto;
}
</style>
